﻿using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using System.Linq;
using Microsoft.SharePoint.Client;
using System.Text;
using Microsoft.SharePoint.Navigation;
using Motesrummet.Common.Constants;
using Motesrummet.Web.Helpers;





namespace Motesrummet.CreateDeleteSiteWebPart
{
    public partial class CreateDeleteSiteWebPartUserControl : UserControl
    {
        string SiteURL;
        string SiteTitle;
        string SiteDescription;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                PopulateDropdowns();
            }
            else
            {
            }
        }


        /// <summary>
        /// Button: Create sub-site
        /// </summary>
        protected void btn_CreateSite_Click(object sender, EventArgs e)
        {
            SPWeb web = SPContext.Current.Site.RootWeb;

            try
            {
                web.AllowUnsafeUpdates = true;
                SetGUIValues();
                SPWebTemplate template = GetTemplate(web);
                
                using (SPWeb myWeb = SPContext.Current.Site.OpenWeb(SiteURL))
                {
                    if (!String.IsNullOrEmpty(SiteURL) && !String.IsNullOrEmpty(SiteTitle) && !myWeb.Exists)
                    {

                        SPWeb newWeb = CreateNamnd(web, template);
                        SetMasterPage(myWeb, newWeb);
                        ResetGUIValues();
                        SetStatusLabel(String.Format(SiteTitle));
                        AddWebToDeleteSitesDropdown(newWeb.Title, newWeb.ID);
                        UpdateNavigation();
                        
                    }
                    else if (String.IsNullOrEmpty(SiteURL) || String.IsNullOrEmpty(SiteTitle))
                    {
                        SetStatusLabel("Sidan måste ha ett URL-namn och en Titel");
                 
                    }
                    else
                    {
                        SetStatusLabel("Siten finns redan");
                      
                    }
                }
            }

            catch (Exception ex)
            {
                ex.Message.ToString();
            }
            finally
            {
                web.AllowUnsafeUpdates = false;
            }
        }

        private void SetStatusLabel(string message)
        {
            lbl_CreateSite.Text = message;
        }

      
      
        private static void SetMasterPage(SPWeb myWeb, SPWeb newWeb)
        {
            var root = myWeb.Site.RootWeb.Url;
            var siteMaster = new Uri(root +
                             "/_catalogs/masterpage/" +
                             "v5.Master");
            newWeb.CustomMasterUrl = siteMaster.AbsolutePath;

            var systemMaster = new Uri(root +
                               "/_catalogs/masterpage/" +
                               "v5.Master");
            newWeb.MasterUrl = systemMaster.AbsolutePath;


            newWeb.Update();
        }

        private SPWeb CreateNamnd(SPWeb web, SPWebTemplate template)
        {
            SPWeb newWeb = web.Site.AllWebs.Add(SiteURL, SiteTitle, SiteDescription, 1033, template, true, false);
            return newWeb;
        }

        private void UpdateNavigation()
        {
            using (SPSite site = new SPSite(SPContext.Current.Site.ID))
            {

                    using (SPWeb webb = site.OpenWeb(SiteURL))
                    {
                        NavigationHelper.CreateNavigation(site, webb, SiteTitle, SiteURL);
                        //Navigation nav = new Navigation();
                        //nav.createNavigation(SiteTitle, SiteURL);
                    }
               
            }
        }

        private void ResetGUIValues()
        {
            txt_Url.Text = string.Empty;
            txt_Title.Text = string.Empty;
            txt_Description.Text = string.Empty;
        }

        private static SPWebTemplate GetTemplate(SPWeb web)
        {
            SPWebTemplate template = web.GetAvailableWebTemplates((uint)1033)
                                                                   .Cast<SPWebTemplate>()
                                                                   .Where(x => x.Title.Equals(MotesrummetConstants.WebTemplates.TemplateName))
                                                                   .First();
            return template;
        }

        private void SetGUIValues()
        {

            SiteURL = txt_Url.Text;
            SiteTitle = txt_Title.Text;
            SiteDescription = txt_Description.Text;
        }

        /// <summary>
        /// Button: Delete sub-site
        /// </summary>
        protected void btn_DeleteSite_Click(object sender, EventArgs e)
        {
            SPSite site = SPContext.Current.Site;

            using (SPWeb web = site.OpenWeb())
            {
                SPWebCollection webColl = web.GetSubwebsForCurrentUser();

                string selVal = drpd_WebSites.SelectedValue;

                var result = (from w in webColl
                              where w.Title.Equals(selVal)
                              select w).FirstOrDefault();

                try
                {
                    lbl_DeleteSite.Text = "Success: Sidan: <b>" + result.Title + "</b> togs bort.";
                    //Ta bort från dropdown

                    drpd_WebSites.Items.Remove(result.Title);
                    //ta bort sidan (från collection)
                    result.Delete();
                }

                catch (Exception)
                {
                    lbl_CreateSite.Text = "Error: Sidan finns inte?";
                }
            }
        }

        private void AddWebToDeleteSitesDropdown(string title, Guid guid)
        {
            drpd_WebSites.Items.Add(new ListItem(title, guid.ToString()));
        }

        /// <summary>
        /// Populates dropdown with...
        /// </summary>
        private void PopulateDropdowns()
        {
            //SiteCollection som vi befinner oss i
            SPSite site = SPContext.Current.Site;

            //Web som finns i ovanstående SiteColl
            using (SPWeb web = site.OpenWeb())
            {
                //Ta fram alla subsites för current user (inte top-site)
                SPWebCollection sub = web.GetSubwebsForCurrentUser();
                //Loopa igenom subKollektionen och lägg till i dropdownlistan.
                foreach (SPWeb subsites in sub)
                {
                    drpd_WebSites.Items.Add(subsites.Title);
                    subsites.Dispose();
                }
            }
        }



    }
}
